package com.qkl.xiatang.app.utils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileTypeFilter {
    private static String[] forbidType = new String[]{"jsp", "php"};
    static final HashMap<String, String> fileTypeMap = new HashMap();

    public FileTypeFilter() {
    }

    private static String getFileTypeBySuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
    }

    public static void fileTypeFilter(MultipartFile file) throws Exception {
        String suffix = getFileType(file);
        String[] var2 = forbidType;
        int var3 = var2.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String type = var2[var4];
            if (type.contains(suffix)) {
                throw new Exception("上传失败，文件类型异常：" + suffix);
            }
        }

    }

    private static String getFileType(MultipartFile file) throws Exception {
        String fileExtendName = null;

        try {
            InputStream is = file.getInputStream();
            byte[] b = new byte[10];
            is.read(b, 0, b.length);
            String fileTypeHex = String.valueOf(bytesToHexString(b));
            Iterator keyIter = fileTypeMap.keySet().iterator();

            String fileName;
            while(keyIter.hasNext()) {
                fileName = (String)keyIter.next();
                if (fileName.toLowerCase().startsWith(fileTypeHex.toLowerCase().substring(0, 5)) || fileTypeHex.toLowerCase().substring(0, 5).startsWith(fileName.toLowerCase())) {
                    fileExtendName = (String)fileTypeMap.get(fileName);
                    break;
                }
            }

            if (StringUtils.isBlank(fileExtendName)) {
                fileName = file.getOriginalFilename();
                return getFileTypeBySuffix(fileName);
            } else {
                is.close();
                return fileExtendName;
            }
        } catch (Exception var7) {
            throw new Exception(var7.getMessage(), var7);
        }
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src != null && src.length > 0) {
            for(int i = 0; i < src.length; ++i) {
                int v = src[i] & 255;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }

                stringBuilder.append(hv);
            }

            return stringBuilder.toString();
        } else {
            return null;
        }
    }

    static {
        fileTypeMap.put("3c25402070616765206c", "jsp");
        fileTypeMap.put("3c3f7068700a0a2f2a2a0a202a205048", "php");
    }
}